package com.example.zhongyingkaoshi.controller;

import org.springframework.stereotype.Component;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.*;


// 添加组件注解
@Component
public class EmailSender {
    // 保留邮件配置信息
    private static final String SMTP_HOST = "smtp.mxhichina.com";
    private static final int SMTP_PORT = 587;
    private static final String EMAIL_USER = "csdims@unitechs.com";
    private static final String EMAIL_PASSWORD = "dZ8DjmgTPq4TGWC0";
    private static final String RECIPIENT_EMAIL = "yuweihan@unitechs.com";

    // 改为public方法供其他类调用
    // 移除static修饰符改为实例方法
    public void sendEmail(String subject, String content) throws MessagingException {
        try {
            Properties props = new Properties();
            props.put("mail.smtp.host", SMTP_HOST);
            props.put("mail.smtp.port", SMTP_PORT);
            props.put("mail.smtp.auth", "true");
            props.put("mail.smtp.starttls.enable", "true");
        
            Session session = Session.getInstance(props, new Authenticator() {
                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(EMAIL_USER, EMAIL_PASSWORD);
                }
            });
        
            Message message = new MimeMessage(session);
            message.setFrom(new InternetAddress(EMAIL_USER));
            message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(RECIPIENT_EMAIL));
            message.setSubject(subject);
            message.setText(content);
        
            Transport.send(message);
        } catch (MessagingException e) {
            System.err.println("邮件发送失败: " + e.getMessage());
            throw e; // 重新抛出异常供上层处理
        }
    }
}